package com.masterclient.app.modules.timelimited;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.bean.firstpager.RecommendPagerBean;
import com.eoner.baselibrary.utils.TimeUtil;
import com.eoner.baselibrary.utils.UtilCollection;
import com.masterclient.app.BaseFragment;
import com.masterclient.app.R;
import com.masterclient.app.base.CashCommonDialog;
import com.masterclient.app.businessmodule.usermodule.login.index.QuickLoginActivity;
import com.masterclient.app.modules.goods.newpage.activity.NewCommodityDetailActivity;
import com.masterclient.app.modules.timelimited.adapter.TimeLimitedBuyAdapter;
import com.masterclient.app.modules.timelimited.contract.TimeLimitedProductsContract;
import com.masterclient.app.modules.timelimited.contract.TimeLimitedProductsContractPresenter;
import com.masterclient.app.modules.timelimited.model.TimeProductsBeanData;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;



public class TimeLimitedBuyFragment extends BaseFragment<TimeLimitedProductsContractPresenter> implements TimeLimitedProductsContract.View{

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;

    @BindView(R.id.desc)
    TextView desc;
    @BindView(R.id.day)
    TextView day;
    @BindView(R.id.hour)
    TextView hour;
    @BindView(R.id.minute)
    TextView minute;
    @BindView(R.id.seconds)
    TextView seconds;

    @BindView(R.id.day_layout)
    View day_layout;
    @BindView(R.id.time_layout)
    View time_layout;

    @BindView(R.id.time_left_layout)
    View time_left_layout;

    TimeLimitedBuyAdapter adapter;

    private List<RecommendPagerBean.ShProduct> list;
    private int total;
    View emptyView;

    String location = "";
    String status = "";
    String sh_event_map_id = "";
    String sh_lifetime;
    String status_title = "";
    String start_time = "";
    String end_time = "";
    String intentSource = "";

    String sh_next_page = "1";

    private int page_no = 1;
    private String remindState;

    //1 昨日精选，2 已结束，3 正在疯抢，4 即将开始，5 明日预告


    public static TimeLimitedBuyFragment getInstance(String location, String status
            , String sh_lifetime, String sh_event_map_id, String status_title,
            String start_time,String end_time, String intentSource) {
        TimeLimitedBuyFragment timeLimitedBuyFragment = new TimeLimitedBuyFragment();
        Bundle bundle = new Bundle();
        bundle.putString("location", location);
        bundle.putString("status", status);
        bundle.putString("sh_event_map_id", sh_event_map_id);
        bundle.putString("sh_lifetime", sh_lifetime);
        bundle.putString("status_title",status_title);
        bundle.putString("start_time",start_time);
        bundle.putString("end_time",end_time);
        bundle.putString("intentSource", intentSource);
        timeLimitedBuyFragment.setArguments(bundle);
        return timeLimitedBuyFragment;
    }

    @Override
    protected View getRootView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_time_limited_buy, null);
    }


    CountDownTimer timer;
    long millisInFuture = 0;
    long countDownInterval = 1000;

    @Override
    protected void initOnlyOnce() {
        super.initOnlyOnce();

        this.location = (String) getArguments().get("location");
        this.status = (String) getArguments().get("status");
        this.sh_event_map_id = (String) getArguments().get("sh_event_map_id");
        sh_lifetime = getArguments().getString("sh_lifetime");
        status_title = getArguments().getString("status_title");
        start_time = getArguments().getString("start_time");
        end_time = getArguments().getString("end_time");
        intentSource = getArguments().getString("intentSource");


        if ("3".equals(status)) {
            try {
                day.setText(TimeUtil.formatTime(TimeUtil.strToLong(end_time), "yyyy年MM月dd日 HH:mm "));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            desc.setText("结束");
        } else if ("4".equals(status) | "5".equals(status)) {
            try {
                day.setText(TimeUtil.formatTime(TimeUtil.strToLong(start_time), "yyyy年MM月dd日 HH:mm "));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            desc.setText("开售");
        }


        millisInFuture = Long.valueOf(sh_lifetime) * 1000;

        if (millisInFuture != 0) {
            millisInFuture += 200;
        }

//        if(sh_lifetime.size() == 4){
//            millisInFuture = Integer.valueOf(sh_lifetime.get(0)) * 24 * 60 * 60 * 1000 +
//                    Integer.valueOf(sh_lifetime.get(1))  * 60 * 60 * 1000 +
//                    Integer.valueOf(sh_lifetime.get(2))  * 60 * 1000 +
//                    Integer.valueOf(sh_lifetime.get(3))  * 1000 + 200;
//        }else if(sh_lifetime.size() == 3){
//            millisInFuture = Integer.valueOf(sh_lifetime.get(0))  * 60 * 60 * 1000 +
//                    Integer.valueOf(sh_lifetime.get(1))  * 60 * 1000 +
//                    Integer.valueOf(sh_lifetime.get(2))  * 1000 + 200;
//        }
        if (millisInFuture != 0) {
//            timer = new CountDownTimer(millisInFuture, countDownInterval) {
//                @Override
//                public void onTick(long millisUntilFinished) {
//                    int day_ = (int) (millisUntilFinished / (1000 * 60 * 60 * 24));
//                    int dayLeft = (int) (millisUntilFinished % (1000 * 60 * 60 * 24));
//                    int hour_ = (int) (dayLeft / (1000 * 60 * 60));
//                    int houtLeft = (int) (millisUntilFinished % (1000 * 60 * 60));
//                    int minute_ = (int) (houtLeft / (1000 * 60));
//                    int minuteLeft = (int) (millisUntilFinished % (1000 * 60));
//                    int seconds_ = (int) (minuteLeft / (1000));
//                    int secondsLeft = (int) (minuteLeft % (1000));
//                    if (day_ == 0) {
//                        day_layout.setVisibility(View.GONE);
//                    } else {
//                        day_layout.setVisibility(View.VISIBLE);
//                    }
//                    setTimeText(day, day_);
//                    setTimeText(hour, hour_);
//                    setTimeText(minute, minute_);
//                    setTimeText(seconds, seconds_);
//
//                    if ("3".equals(status)) {
//                        desc.setText("距本场结束");
//                    } else if ("4".equals(status) | "5".equals(status)) {
//                        desc.setText("距本场开始");
//                    }
//
//                }
//
//                @Override
//                public void onFinish() {
//                    if ("4".equals(status) | "5".equals(status)) {
//                        status = "3";
//                        adapter.setStatus(status);
//                    } else if ("1".equals(status) | "3".equals(status)) {
//                        status = "2";
//                        adapter.setStatus(status);
//                    }
//                    refresh();
//                }
//            };
//            timer.start();
        } else {
            desc.setText("本场已结束,下次早点吧～");
            day_layout.setVisibility(View.GONE);
            time_layout.setVisibility(View.GONE);
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));

        if (millisInFuture == 0) {
            status = "2";
        }
        adapter = new TimeLimitedBuyAdapter(status);
        recyclerView.setAdapter(adapter);

        DividerItemDecoration divider = new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(mContext, R.drawable.homepage_time_divider));
        recyclerView.addItemDecoration(divider);

        adapter.bindToRecyclerView(recyclerView);
        emptyView = View.inflate(mContext, R.layout.empty_time_limited, null);
        emptyView.setVisibility(View.GONE);
        TextView tvTip = (TextView) emptyView.findViewById(R.id.tv_tip);
        TextView tvDesc = (TextView) emptyView.findViewById(R.id.tv_desc);
        tvDesc.setText("未来的你会感谢现在正在奋斗的自己");
        adapter.setEmptyView(emptyView);


        swipeLayout.setOnRefreshListener(() -> {
            refresh();
        });

        adapter.setOnLoadMoreListener(() -> {
            if ("1".equals(sh_next_page)) {
                page_no++;
                mPresenter.getProducts(location, status, "" + page_no, sh_event_map_id);
            }
        }, recyclerView);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivitryWithBundle(NewCommodityDetailActivity.class, new String[][]{{"id", list.get(position).getSh_id()}
                        ,{"source_page","限时抢购"},{"source_module", list.get(position).getSh_s_flashsale_starttime()},{"source_position",position+""}});
            }
        });
        adapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.buy_btn) {
                remindState = list.get(position).getSh_remind_state();
                switch (remindState) {
                    case "0":
                        //其他
                        startActivitryWithBundle(NewCommodityDetailActivity.class, new String[][]{{"id", list.get(position).getSh_id()}
                        ,{"source_page","限时抢购"},{"source_module", list.get(position).getSh_s_flashsale_starttime()},{"source_position",position+""}});
                        break;
                    case "1":
                        //1: 未开抢（开抢提醒)
                        if (isLogin()) {
                            //是否开启通知
                            if (!UtilCollection.isNotificationEnabled(getActivity())) {
                                display_notification_tip_dialog();
                            } else {
                                mPresenter.setSaleRemain(sh_event_map_id, list.get(position).getSh_id(), remindState);
                            }
                        } else {
                            startActivity(new Intent(mContext, QuickLoginActivity.class));
                        }
                        break;
                    case "2":
                        //2: 取消提醒
//                        if (isLogin()) {
//                            if (!UtilCollection.isNotificationEnabled(getActivity())) {
//                                display_notification_tip_dialog();
//                            } else {
//                                mPresenter.setSaleRemain(sh_event_map_id, list.get(position).getSh_id(), remindState);
//                            }
//                        } else {
//                            startActivity(new Intent(mContext, QuickLoginActivity.class));
//                        }
                        break;
                }
            }
        });
    }

    private CashCommonDialog ids_dialog;

    private void display_notification_tip_dialog() {
        if (ids_dialog == null) {
            ids_dialog = new CashCommonDialog(mContext, "系统通知未开启，活动开始后无法第一时间通知到您哦，快去开启通知吧！", "取消", "开启", 2);
        }
        ids_dialog.setOnChooseListerner(new CashCommonDialog.OnChooseListerner() {
            @Override
            public void cancel() {
                ids_dialog.dismiss();
            }

            @Override
            public void confirm() {
                ids_dialog.dismiss();
                UtilCollection.requestNotify(getActivity());
            }
        });
        ids_dialog.show();
    }

    @Override
    public void onResume() {
        super.onResume();
        refresh();
    }

    private void refresh() {
        if (list != null) {
            list.clear();
            adapter.notifyDataSetChanged();
        }
        emptyView.setVisibility(View.GONE);
        page_no = 1;
        mPresenter.getProducts(location, status, "" + page_no, sh_event_map_id);
    }

    private void setTimeText(TextView day, int day_) {
        if (("" + day_).length() == 1) {
            day.setText("0" + day_);
        } else {
            day.setText("" + day_);
        }
    }

    public void refreshList() {
        if (list != null) {
            list.clear();
            adapter.notifyDataSetChanged();
        }
        mPresenter.getProducts(location, status, "" + page_no, sh_event_map_id);
    }

    @Override
    public void showData(TimeProductsBeanData data) {

        if (swipeLayout != null && swipeLayout.isRefreshing()) {
            swipeLayout.setRefreshing(false);
        }

        //total = Integer.valueOf(bean.getSh_total_rows());
        if (list == null) {
            list = new ArrayList<>();
        }

        list.addAll(data.getSh_list());
        adapter.setNewData(list);
        if (list.size() <= 0) {
            emptyView.setVisibility(View.VISIBLE);
            time_left_layout.setVisibility(View.GONE);
        } else {
            time_left_layout.setVisibility(View.VISIBLE);
        }

        sh_next_page = data.getSh_next_page();

        if ("0".equals(sh_next_page)) {
            adapter.setEnableLoadMore(false);
        }


    }

    @Override
    public void loadFail(String s) {
        if (swipeLayout != null && swipeLayout.isRefreshing()) {
            swipeLayout.setRefreshing(false);
        }
        emptyView.setVisibility(View.VISIBLE);
        time_left_layout.setVisibility(View.GONE);
    }

    @Override
    public void loadError(String s) {
        time_left_layout.setVisibility(View.GONE);
    }

    @Override
    public void setSaleRemainSuccess() {
        refresh();
        if ("1".equals(remindState)) {
            ToastUtil.showToast("预约成功，系统会在活动开始前5分钟通知您");
        }
    }

    @Override
    public void setSaleRemainFail(String s) {
        ToastUtil.showToast(s);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }
}
